import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import { MemberVo } from 'src/app/model/member-vo';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { MemberService } from 'src/app/services/member.service';
import { UtilService } from 'src/app/services/util.service';
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'app-personal-avatar',
  templateUrl: './personal-avatar.component.html',
  styles: [``]
})
export class PersonalAvatarComponent implements OnInit {
  public curMember: MemberVo | null;
  //所有可用的头像对象:{id,link,name}
  public items: {id:number,name:string,link:string}[] = [];
  public forceAvatarFileName: string = '';
  private token: string = '';
  private ip: string = '127.0.0.1';

  constructor(
    private title: Title,
    private http: HttpClient,
    private memberStorage: MemberStorageService,
    private memberService: MemberService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.token = this.util.randomAlphaNumeric(8) || '123456';
    this.curMember = this.memberStorage.get();
    this.btnNaviSharedService.active(false);//不需要全局的导航
    this.memberStorage.getIpCliente().subscribe(ipAddr=>this.ip=ipAddr);

  }

  ngOnInit(): void {
    this.title.setTitle('个人中心:选择头像');
    this.getAvatarJson();
    this.forceAvatarFileName = this.currentMemberAvatarFileName();
  }
  //更新头像
  public updateAvtar(chooseFileName: string): void {
    //x.jpeg
    this.memberService.editAvatar(this.curMember?.id ?? 0, '/' + environment.avatarTheme + '/' + chooseFileName, environment.domain, environment.avatarDirect, this.token, this.ip).subscribe({
      next: response => {
        let decodeAvatarPath: string = response;
        //更新cache
        this.memberStorage.updateStorage(this.curMember?.id ?? 0, { avatar: decodeAvatarPath });
        this.forceAvatarFileName = chooseFileName;
        this.util.alertSuccess('头像更新成功');
      },
      error: err => {
        this.util.alertError('头像更新失败');
      },
      complete: () => {
        console.log('[PersonalAvatar-CTL]edit avatar Completed');
      }
    });
  }
  public changeStyle(event: Event): void {
    const targetElement: HTMLImageElement = event.target as HTMLImageElement;
    if (targetElement.getAttribute('data-file') === this.forceAvatarFileName) {
      //不在当前选中的头像上触发
      return;
    }
    if (event.type == 'mouseover') {
      targetElement.style.backgroundColor = '#f00';
    }
    if (event.type == 'mouseout') {
      targetElement.style.backgroundColor = '#fff';
    }
  }
  //从JSON文件中获取头像的信息
  private getAvatarJson(): void {
    this.http.get(environment.avatarJsonPath).subscribe((data: any) => {
      if (data.hasOwnProperty(environment.avatarTheme)) {
        let atv = environment.avatarTheme;
        this.items = data[atv];
      }
    },
      (err: HttpErrorResponse) => {
        console.log('[PersonalAvatar-CTL]avatar json query: ' + err.message);
      });
  }

  private currentMemberAvatarFileName(): string {
    let a = this.curMember?.avatar ?? 'empty.png'; //avtar://local/default/16.jpeg
    if (a.indexOf('/') != -1) {
      //let segment:string[] = a.split('/');
      return a.split('/').pop() || 'empty.png';
    }
    return 'empty.png';
  }
}
